/**
 * Copyright (C), 2015-2020, 云帐房
 * FileName: HttpRemoveDataSource
 * Author:   cjz
 * Date:     2020/5/14 上午11:02
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.yzf.wisecoder.remotedata;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import com.yzf.cframework.common.http.HttpUtils;
import com.yzf.cframework.common.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName : HttpRemoveDataSource
 * @Description : http 接口获取远端数据
 * @Author : cjz
 * @Date: 2020-05-14 11:02
 */
@Slf4j
public class ElasticSearchRemoteDataSource extends AbstractRemoteDataSource {

    public ElasticSearchRemoteDataSource(RemoteInfo remoteInfo) {
        super(remoteInfo);
    }

    @Override
    public ElasticSearchRemoteDataSource execute() {
//        result = HttpUtils.sendPost(remoteInfo.getUrl(), remoteInfo.getExecute());
        String url = String.format("%s/_search", remoteInfo.getUrl());
//        result = HttpUtil.createPost(url).body(remoteInfo.getExecute()).execute().body();
        result = HttpUtils.HttpPostWithJson(url, remoteInfo.getExecute());
        System.out.println(result);
        return this;
    }

    @Override
    public List<Map> result() {
        JSONObject jsonObject = JsonUtils.parseObject(result.toString());
        if (!jsonObject.containsKey("hits")){
            return null;
        }
        JSONObject hitsObject = jsonObject.getJSONObject("hits");
        log.debug("Hits total:{}",hitsObject.get("total"));
        List<Map>  result = hitsObject.getJSONArray("hits").toJavaList(Map.class);

        return result;
    }

}
